<?php
define('COLOR_NAME', 'Farve');
define('SIZE_NAME', 'Størrelse');

function getdata(){
	try {
		$url = "http://api.dddadmin.com/StockService.svc?wsdl";
		$client = new SoapClient($url);
		
		
		$shopid = "855001";
		$myKey	= "vkal29xcjs81lslc8qlxpgg63anxaqk2ixkskxm19m";
		
		$params['clientid'] = "855001";
		$params['psk'] = "vkal29xcjs81lslc8qlxpgg63anxaqk2ixkskxm19m";
		
		
		$articles = $client->GetWebshopArticles($params);
		$strInfo = ($articles->GetWebshopArticlesResult);
		$arrInfo = json_decode($strInfo);
		
		$sizeInfo = array_chunk($arrInfo, 1000);
		$folder = 'product/';
		foreach($sizeInfo as $key=>$value){
			$file = fopen($folder. $key.'.txt', 'w');
			fwrite($file, serialize($value));
			fclose($file);
		}
		
		
	}
	catch (SoapFault $exception) {
		echo $exception->getMessage();
	}

}

function group_assoc($array, $key) {
    $return = array();
    foreach($array as $v) {
        $return[$v[$key]][] = $v;
    }
    return $return;
}

function toArray($obj)
{
    if (is_object($obj)) $obj = (array)$obj;
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = toArray($val);
        }
    } else {
        $new = $obj;
    }
    return $new;
}


function getAttributeId($db, $KatalogNumber, $name){
	$attribute = $db->fetch_row('katalognumber = ' . $KatalogNumber .", name = '" . $name ."'", 'attribute' , FETCH_ASSOC);
	$exists = $db->get_rows();
	if(!empty($exists)){
		return $attribute[0]['attribute_id'];
	}
	return '';
}

function getAttributeValueId($db, $attribute_id, $name){
	$attribute_value = $db->fetch_row('attribute_id = ' . $attribute_id .", name = '" . $name ."'", 'attribute_value', FETCH_ASSOC);
	$exists = $db->get_rows();
	if(!empty($exists)){
		return $attribute_value[0]['value_id'];
	}
	return '';

}

function getStockcount($ean, $arrStock){
	$count = '0';
	foreach($arrStock as $key=>$value){
		if($ean == $value['Key']){
			$count = $value['Value'];
			break;
		}
	}
	return $count;
}

function getProductid($db, $KatalogNumber, $vparam1){
	$product_row = $db->fetch_row('katalognumber = ' . $KatalogNumber .", vparam1 = '" . $vparam1 ."'", 'product', FETCH_ASSOC);
	$exists = $db->get_rows();
	if(!empty($exists)){
		return $product_row[0]['product_id'];
	}
	return '';
}

function addSizetoproduct2($db, $product_id, $quantity, $attribute_id, $size){
	//echo $product_id . "<br />";
	$db->query("BEGIN");
	//$error = true;
	$product_option_row = $db->fetch_row('product_id = ' . $product_id . ", attribute_id = " . $attribute_id, 'product_option', FETCH_ASSOC);
	//echo $db->get_lastquery() . "<br />";
	$exists = $db->get_rows();
	if(empty($exists)){
		//$db->query('LOCK TABLES product_option WRITE');
		$fields = array('product_id','attribute_id');
		$data = array($product_id, $attribute_id);
		$product_option_id = $db->insert($fields, $data, 'product_option');
		//echo $db->get_lastquery() . "<br />";
		//$db->query('UNLOCK TABLES');
		
		//$db->query('LOCK TABLES product_option_description WRITE');
		$fields = array('product_option_id','language_id','product_id','name');
		$data = array($product_option_id, '1', $product_id, 'Størrelse' );
		$error = $db->insert($fields, $data, 'product_option_description');
		//echo $db->get_lastquery() . "<br />";
		//$db->query('UNLOCK TABLES');
	}else{
		$product_option_id = $product_option_row[0]['product_option_id'];
	}
	

	$attribute_value_id = getAttributeValueId($db, $attribute_id, $size );
	$product_option_value_row = $db->fetch_row('product_option_id = ' . $product_option_id . 
	", product_id = " . $product_id .
	", attribute_id = " .$attribute_id . ", attribute_value_id = " . $attribute_value_id, 'product_option_value', FETCH_ASSOC);
	//echo $db->get_lastquery() . "<br />";
	$exists1 = $db->get_rows();
	if(empty($exists1)){
	
		
		//$db->query('LOCK TABLES product_option_value WRITE');
		$fields = array('product_option_id','product_id','quantity','attribute_id','attribute_value_id');
		$data = array($product_option_id, $product_id, $quantity , $attribute_id, $attribute_value_id);
		$product_option_value_id = $db->insert($fields, $data, 'product_option_value');
		//echo $db->get_lastquery() . "<br />";
		//$db->query('UNLOCK TABLES');
		$error = $product_option_value_id;
		
		//$db->query('LOCK TABLES product_option_value_description WRITE');
		$fields = array('product_option_value_id','language_id','product_id','name');
		$data = array($product_option_value_id, '1', $product_id, $size);
		$error = $db->insert($fields, $data, 'product_option_value_description');
		//echo $db->get_lastquery() . "<br />";
		//$db->query('UNLOCK TABLES');
		
	}else{
		$product_option_value_id = $product_option_value_row[0]['product_option_value_id'];
		$fields = array('quantity');
		$data = array($quantity);
		$error = $db->update($fields, $data, 'product_option_value_id = ' . $product_option_value_id , 'product_option_value');
		//echo $db->get_lastquery() . "<br />";
		
	}
	//echo $db->get_lastquery() . "<br />";
	
	
	$db->query("COMMIT");
		
	return true;
	/*	
	if(!$error){  
		//echo $db->get_lastquery();
		$db->query("COMMIT");
		
		return true;
		
	}else{  
		//echo "Error:  [".$db->get_lastquery()."]" ."-" . mysql_error() . "<br />";  
		//$content .= "\n\r Error:  [".$db->get_lastquery()."]" ."-" . mysql_error();  
		//$content .= "\n\r----- ERROR --------\n\r";
		$db->query("ROLLBACK");
		return false;
	}
	*/
	
}
function insertProduct($db,  $myproduct, $color){
	$supplier = $myproduct['Supplier']; 
	$itemgroup = $myproduct['ItemGroup'];
	$KatalogNumber = $myproduct['KatalogNumber'];
	$manufacturer = $db->fetch_row('supplier = ' . $supplier, 'manufacturer', FETCH_ASSOC);
	$exists = $db->get_rows();
	$category = $db->fetch_row('itemgroup = ' . $itemgroup, 'category', FETCH_ASSOC);
	$exists1 = $db->get_rows();
	
	if(!empty($exists) && !empty($exists1)){
		$manufacturer_id = $manufacturer[0]['manufacturer_id'];
		//product
		$db->query('LOCK TABLES product WRITE');
		/*
		$fields = array('sku','stock_status_id','manufacturer_id','date_available','date_added', 'katalognumber', 'vparam1', 'price' );
		$data = array( $myproduct['Kparam1'], '5', $manufacturer_id, date('Y-m-d'), date('Y-m-d'), $KatalogNumber, $color, $myproduct['SalesPriceEach']);
		*/
		$fields = array('sku','stock_status_id','manufacturer_id','date_available','date_added', 'tax_class_id', 'katalognumber', 'vparam1', 'price' );
		$data = array( $myproduct['Kparam1'], '5', $manufacturer_id, date('Y-m-d'), date('Y-m-d'), '9', $KatalogNumber, $color, $myproduct['SalesPriceEach']);
		$product_id = $db->insert($fields, $data, 'product');
		$db->query('UNLOCK TABLES');
		
		//product_description
		$db->query('LOCK TABLES product_description WRITE');
		$fields = array('product_id','language_id','name');
		$data = array($product_id, '1', $myproduct['Kparam2'] . " - " . $color);
		$db->insert($fields, $data, 'product_description');
		$db->query('UNLOCK TABLES');
		
		//product_to_category
		$db->query('LOCK TABLES product_to_category WRITE');
		$category_id = $category[0]['category_id'];
		$fields = array('product_id','category_id');
		$data = array($product_id, $category_id);
		$db->insert($fields, $data, 'product_to_category');
		$db->query('UNLOCK TABLES');
		
		//product_to_store
		$db->query('LOCK TABLES product_to_store WRITE');
		$fields = array('product_id','store_id');
		$data = array($product_id, '0');
		$db->insert($fields, $data, 'product_to_store');
		$db->query('UNLOCK TABLES');
	}
	return $product_id;
}

function updateProduct($db, $product_id, $myproduct, $color){

	//$supplier = $myproduct['Supplier']; 
	//$itemgroup = $myproduct['ItemGroup'];
	
	//$manufacturer = $db->fetch_row('supplier = ' . $supplier, 'manufacturer', FETCH_ASSOC);
	//$exists = $db->get_rows();
	//$category = $db->fetch_row('itemgroup = ' . $itemgroup, 'category', FETCH_ASSOC);
	//$exists1 = $db->get_rows();
	
	//if(!empty($exists) && !empty($exists1)){
		//product
		//$manufacturer_id = $manufacturer[0]['manufacturer_id'];
		
		//$fields = array('sku','stock_status_id','manufacturer_id', 'date_modified');
		//$data = array( $myproduct['Kparam1'], '5', $manufacturer_id, date('Y-m-d'));
		
		//Note: dont update the manufactuere id because the client can change it on web
		$fields = array('sku' ,'date_modified', 'tax_class_id');
		$data = array( $myproduct['Kparam1'], date('Y-m-d'), '9');
		
		$db->update($fields, $data, 'product_id = ' . $product_id, 'product');

		//product_description
		/*
		$product_name = $myproduct['Kparam2'] . " - " . $color;
		
		$fields = array('language_id','name');
		$data = array('1', $product_name);
		$db->update($fields, $data, 'product_id = ' . $product_id, 'product_description');
		*/
		
		//product_to_category
		//dont update the category 
		
		/*
		$category_id = $category[0]['category_id'];
		$fields = array('category_id');
		$data = array($category_id);
		$db->update($fields, $data, 'product_id = ' . $product_id, 'product_to_category');
		*/
	//}
	
	return $product_id;
	
}

function insertManufacturers($db, $arr_manufacturer){
	$error = false;
	$result = true;
	$db->query("BEGIN");
	
	if(count($arr_manufacturer)){
		foreach($arr_manufacturer as $key=>$value){
			$db->fetch_row('supplier = ' . $key,'manufacturer');
			$exists = $db->get_rows();		
			if(empty($exists)){
				$fields = array('supplier', 'name', 'status');
				$data = array($key, "T - " . $value, '0');
				$manufacturer_id = $db->insert($fields, $data, 'manufacturer');
				if(!$manufacturer_id){
					$error = true;
					break;
				}
				$fields = array('manufacturer_id', 'store_id');
				$data = array($manufacturer_id, '0');
				$db->insert($fields, $data, 'manufacturer_to_store');
				
			}else{
				/*
				$fields = array( 'name');
				$data = array( "T - " . $value);
				
				$db->update($fields, $data, 'supplier = ' . $key, 'manufacturer');
				*/
			}
		}
			

		if(!$error){  
		//*** Commit Transaction ***//  
			$db->query("COMMIT");  
			return true;
			
		}else{  
			//*** RollBack Transaction ***//  
			//echo "Error:  [".$db->get_lastquery()."]" ."-" . mysql_error();  
			$db->query("ROLLBACK");
			return false;
		}
	}

}

function insertCategories($db, $arr_category){
	$terminal = '412';
	$error = false;
	$result = true;
	$db->query("BEGIN");
	if(count($arr_category)){
		foreach($arr_category as $key=>$value){
			$cat = $db->fetch_row('itemgroup = ' . $key,'category', FETCH_ASSOC);
			
			$exists = $db->get_rows();
			if(empty($exists)){
				//check terminal category exists
				
				$db->fetch_row('category_id = ' . $terminal, 'category');
				$exists1 = $db->get_rows();		
				if($exists1){
					
					$fields = array('parent_id','itemgroup','date_added','status');
					$data = array($terminal, $key, date('Y-m-d'), '0'); // add to parent category Terminal ID = 412				
					$category_id = $db->insert($fields, $data, 'category');
					
					if(!$category_id){
						$error = true;
						break;
					}

					$fields = array('category_id', 'language_id',  'name');
					$data = array($category_id, '1', $value);
					$db->insert($fields, $data, 'category_description');

					$fields = array('category_id', 'store_id');
					$data = array($category_id, '0');
					$db->insert($fields, $data, 'category_to_store');

				}
				
			}else{
				/*
				$fields = array('name');
				$data = array($value);
				
				$category_id = $cat[0]['category_id'];
				$result = $db->update($fields, $data, 'category_id = ' . $category_id, 'category_description');
				
				if(!$result){
					$error = true;
					break;
				}
				*/
			}
		}
	}
	if(!$error){  
	//*** Commit Transaction ***//  
		$db->query("COMMIT");  
		return true;
		
	}else{  
		//*** RollBack Transaction ***//  
		//echo "Error:  [".$db->get_lastquery()."]" ."-" . mysql_error();  
		$db->query("ROLLBACK");
		return false;
	}
			
}

function insertAttribute($db, $group_products){

	$error = false;
	$db->query("BEGIN");
	
	foreach($group_products as $KatalogNumber=>$products){
		$value_id = true;
		//group by size
		$group_product_size = group_assoc($products, 'Vparam4');
		//get array with size name
		$arr_sizes = array_keys($group_product_size);
		$size_name = "Størrelse";
		$size_description = $products[0]['SupplierName'] . "|" . $products[0]['ItemGroupName'] . "|" . $products[0]['Kparam2'] . "|" . $products[0]['Kparam1'];
		
		$attribute_id = getAttributeId($db, $KatalogNumber, 'Størrelse');		
		if(empty($attribute_id)){
			//add size 1 time cauze 1 katalogNumber has only 1 size
			$fields = array('name', 'description', 'date_added', 'status', 'kparam1', 'katalognumber');
			$data = array($size_name, $size_description, date('Y-m-d'), "1", $products[0]['Kparam1'], $KatalogNumber);
			$attribute_id = $db->insert($fields, $data, 'attribute');
		}
		if(!$attribute_id){
			$error = true;
			break;
		}
		foreach($arr_sizes as $size){
			$exists = getAttributeValueId($db, $attribute_id, $size);
			if(empty($exists)){
				//add size name to table attribute_value				
				$fields = array('name', 'attribute_id');
				$data = array($size, $attribute_id);
				$value_id = $db->insert($fields, $data, 'attribute_value');				
				if(!$value_id){
					$error = true;
					break;
				}
			}
		}
		if(!$value_id){
			$error = true;
			break;
		}
		
	}
	if(!$error){  
	//*** Commit Transaction ***//  
		$db->query("COMMIT");  
		return true;
		
	}else{  
		//*** RollBack Transaction ***//  
		//echo "Error:  [".$db->get_lastquery()."]" ."-" . mysql_error();  
		$db->query("ROLLBACK");
		return false;
	}
	
}


function insertProducts($db, $group_products){
	$error = false;
	$db->query("BEGIN");
	foreach($group_products as $KatalogNumber=>$products){
		
		//get list with key is color, value is array of product.
		$group_product_color = group_assoc($products, 'Vparam1');
		
		foreach($group_product_color as $color=>$color_products){
			$product = $color_products[0];
			$product = $products[0];
			$KatalogNumber = $product['KatalogNumber'];
			$product_row = $db->fetch_row('katalognumber = ' . $KatalogNumber . ', vparam1 = "'.$color.'"', 'product', FETCH_ASSOC);
			$exists = $db->get_rows();
			
			
			if(empty($exists)){
				$product_id = insertProduct($db, $product, $color);
			}else{
				$product_id = $product_row[0]['product_id'];
				updateProduct($db, $product_id, $product, $color);
			}
		}
	}
	if(!$error){  
	//*** Commit Transaction ***//  
		$db->query("COMMIT");  
		return true;
		
	}else{  
		//*** RollBack Transaction ***//  
		//echo "Error:  [".$db->get_lastquery()."]" ."-" . mysql_error();  
		$db->query("ROLLBACK");
		return false;
	}
}

function insertOptiontoProduct($db, $myarrInfo){
	
	$mystock = file_get_contents('stock.txt');
	$objStock = unserialize($mystock);
	$arrStock = toArray($objStock);
	$error = false;

	if(count($myarrInfo)){
		$index = 1;
		foreach($myarrInfo as $product){
			$KatalogNumber 	= $product['KatalogNumber'];
			$color 			= $product['Vparam1'];
			$product_id 	= getProductid($db, $KatalogNumber, $color);
			$attribute_id 	= getAttributeId($db, $KatalogNumber, 'Størrelse');
			$size 			= $product['Vparam4'];
			$ean 			= $product["Ean"];
			$quantity 		= getStockcount($ean, $arrStock);
			//echo $product_id . " - " . $attribute_id . " - " . $size . " - " . $ean . " - " . $quantity . "<br />";
			
			addSizetoproduct2($db, $product_id, $quantity, $attribute_id, $size);
			$index++;
		}
	}
}

function updateTotalStock($db){
	$product_row = $db->fetch_query('SELECT product_id FROM product WHERE katalognumber != "0" AND vparam1 != "0"', FETCH_ASSOC);

	foreach($product_row as $product){
		$product_id = $product['product_id'];
		$arr_total_quantity = $db->fetch_query('SELECT SUM(quantity) as total FROM product_option_value WHERE attribute_id != 0 AND attribute_value_id != 0 AND product_id = ' . $product_id, FETCH_ASSOC);
		
		$fields=array('quantity');
		$data = array($arr_total_quantity[0]['total']);
		$db->update($fields, $data, 'product_id = ' . $product_id, 'product');
		
		
	}
}
?>